<template>
  <div class="dynamic-cascader-container">
    <!-- 级联选择器  v-model="selectedValue"-->
    <a-cascader
      :options="optionsRoom"
      :load-data="loadDataRoom"
      :change-on-select="false"
      placeholder="请选择"
      expand-trigger="click"
      style="width: 300px"
      @change="handleChange"
    />

    <!-- 显示选中结果 -->
    <!-- <div class="result-display" v-if="selectedValue.length > 0">
      <h3>选择结果：</h3>
      <p>ID路径: {{ selectedValue.join(' / ') }}</p>
      <p>名称路径: {{ selectedPath.join(' / ') }}</p>
    </div> -->
  </div>
</template>

<script>
import { getAction } from '@/api/manage'

// 模拟API请求函数 - 实际项目中替换为真实的API调用
const fetchRegionData = (parentId, level, mockData) => {
  // 模拟API延迟
  console.log('mockData>>', mockData)
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(mockData[parentId] || [])
    }, 800)
  })
}

export default {
  data() {
    return {
      selectedValue: [], // 选中的值数组
      selectedPath: [], // 选中的标签路径
      optionsRoom: [], // 级联选项数据
      cache: new Map(), // 数据缓存
      queryParam: {},
      url: {
        getCampusAreaList: '/system/devCampusArea/getList',
        getCampusBuildingList: 'system/devCampusBuilding/getList',
        getCampusBuildingFloorList: 'system/devCampusBuildingFloor/getList',
        getCampusBuildingFloorRoomlist:
          '/system/devCampusBuildingFloorRoom/getList',
      },
    }
  },
  mounted() {
    this.loadInitialData()
  },
  methods: {
    getCampusAreaList() {
      getAction(this.url.getCampusAreaList).then((res) => {
        console.log('getCampusAreaList>>>', res.result.data)
      })
    },
    /**
     * 初始化加载第一级数据
     */
    async loadInitialData() {
      getAction(this.url.getCampusAreaList).then((res) => {
        console.log('records12>>', res.result.data)
        var records = res.result.data
        var provinces = []
        if (records) {
          records.forEach((item) => {
            provinces.push({
              value: item.id,
              label: item.campusName,
              isLeaf: false,
            })
          })
        }
        console.log('provinces111>>', provinces)
        this.optionsRoom = provinces
        // 缓存第一级数据
        this.cache.set('0', provinces)
        this.$message.destroy()
      })
    },

    /**
     * 动态加载下级数据
     * @param {Array} selectedOptions 已选中的选项数组
     */
    async loadDataRoom(selectedOptions) {
      const targetOption = selectedOptions[selectedOptions.length - 1]
      const cacheKey = targetOption.value

      console.log('cacheKey>>', cacheKey)
      console.log('selectedOptions.length + 1>>', selectedOptions.length + 1)
      // 如果正在加载或已经是叶子节点，则直接返回
      if (targetOption.loading || targetOption.isLeaf) return

      // 显示加载状态
      targetOption.loading = true

      try {
        // 检查缓存
        // if (this.cache.has(cacheKey)) {
        //   targetOption.children = this.cache.get(cacheKey);
        // } else {
        // 调用API获取数据
        console.log('cacheKey>>', cacheKey)
        console.log('selectedOptions.length + 1>>', selectedOptions.length + 1)

        //查询节点
        var level = selectedOptions.length + 1
        //请求地址
        var url = ''
        //请求参数
        var param = {}
        //建筑物
        if (level == 2) {
          url = this.url.getCampusBuildingList
          param = { campusAreaId: cacheKey }
        }

        //楼层
        if (level == 3) {
          url = this.url.getCampusBuildingFloorList
          param = { buildingId: cacheKey }
        }

        //房间
        if (level == 4) {
          url = this.url.getCampusBuildingFloorRoomlist
          param = { floorId: cacheKey }
        }
        var childrenList = await getAction(url, param).then((res) => {
          var records = res.result.data
          console.log('children>>>records:', records)
          if (records) {
            var list = []
            records.forEach((item) => {
              list.push({
                value: item.id,
                label: item.name,
                isLeaf: item.isLeaf,
              })
            })
            return { [cacheKey]: list }
          }
        })
        console.log('data>>', childrenList)
        const children = await fetchRegionData(
          cacheKey,
          selectedOptions.length + 1,
          childrenList
        )

        if (children && children.length > 0) {
          targetOption.children = children
          // 添加到缓存
          //this.cache.set(cacheKey, children);
        } else {
          // 没有子节点则标记为叶子节点
          targetOption.isLeaf = true
        }
        // }
      } catch (error) {
        this.$message.error(`加载 ${targetOption.label} 数据失败`)
        console.error('加载数据失败:', error)
      } finally {
        // 无论成功失败都要取消加载状态
        targetOption.loading = false
        // 触发视图更新
        this.optionsRoom = [...this.optionsRoom]
      }
    },

    /**
     * 选择变化回调
     * @param {Array} value 选中的值数组
     * @param {Array} selectedOptions 选中的选项对象数组
     */
    handleChange(value, selectedOptions) {
      this.selectedValue = value
      this.selectedPath = selectedOptions.map((option) => option.label)
      console.log('选中值:', value)
      console.log('选中路径:', this.selectedPath)
      this.$emit('selectedValue', value)
      this.$emit('change', value)
      this.$emit('ok', value)
    },
  },
  model: {
    prop: 'value',
    event: 'change',
  },
}
</script>

<style scoped>
.dynamic-cascader-container {
  padding: 20px;
  max-width: 600px;
  margin: 0 auto;
}

.result-display {
  margin-top: 20px;
  padding: 15px;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.result-display h3 {
  margin-top: 0;
  color: #333;
}

.result-display p {
  margin: 5px 0;
  color: #666;
}
</style>
